package com.bcxk.common;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator.Builder;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.JWTVerifier;
import org.apache.commons.lang.time.DateUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

public class JwtUtil {
    private static JWTVerifier verifier;
    private static final String SECRET = "A_string_of_arbitrary_length|Also_can_be_the_user's_password.";
    private static final String ISSUER = "PEGASUS";
    private static final String NAME = "JWT_ID";
    public static String createToken(String id) {
        Map<String, String> payload = new HashMap<>();
        payload.put(NAME, id);
        return create(payload);
    }

    public static String analyseToken(String token) {
        DecodedJWT decodedJWT = JwtUtil.verify(token);
        return decodedJWT.getClaim(NAME).asString();
    }

    public static String create(Map<String, String> payload) {
        Algorithm algorithm = Algorithm.HMAC256(SECRET);
        Map<String, Object> headers = new HashMap<String, Object>();
        headers.put("alg", "HS256");
        headers.put("typ", "JWT");
        Builder builder = (Builder) JWT.create() // 创建JWT构建器
                .withJWTId(UUID.randomUUID().toString()) // 设置JWT的ID
                .withHeader(headers) // 设置头部信息
                .withIssuer(ISSUER) // 签名的生成者
                .withSubject("SUBJECT") // 签名主题
                .withNotBefore(new Date()) // 定义在什么时间之前，该JWT都是不可用的
                .withAudience("AUDIENCE") // 签名的接受者
                .withIssuedAt(new Date()) // 生成签名的时间
                .withExpiresAt(DateUtils.addMinutes(new Date(), 10)); // 签名过期时间
        payload.forEach((key, value) -> builder.withClaim(key, value));
        return builder.sign(algorithm);
    }

    public static DecodedJWT verify(String token) {
        Algorithm algorithm = Algorithm.HMAC256(SECRET);
        if (verifier == null) {
            verifier = JWT.require(algorithm).withIssuer(ISSUER).build();
        }
        return verifier.verify(token);
    }
}



